from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from department.models import Department

# Create your views here.

# 部门列表序列化器
class DepartmentListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = ['id', 'name', 'office', 'chairman']

# 部门创建/更新序列化器
class DepartmentCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = ['id', 'name', 'office', 'chairman']

# 部门管理视图
class DepartmentManagementView(APIView):
    """部门管理相关接口"""
    
    def get(self, request, department_id=None):
        """获取部门列表或单个部门详情"""
        try:
            if department_id:
                # 获取单个部门详情
                department = Department.objects.filter(id=department_id).first()
                if not department:
                    res = {
                        'status': 404,
                        'data': {
                            'message': '部门不存在'
                        }
                    }
                    return Response(res, status=status.HTTP_404_NOT_FOUND)
                
                serializer = DepartmentListSerializer(department)
                res = {
                    'status': 200,
                    'data': {
                        'department': serializer.data,
                        'message': '部门详情获取成功'
                    }
                }
            else:
                # 获取所有部门
                departments = Department.objects.all()
                
                # 序列化数据
                serializer = DepartmentListSerializer(departments, many=True)
                
                # 构建响应
                res = {
                    'status': 200,
                    'data': {
                        'total': departments.count(),
                        'list': serializer.data,
                        'message': '部门列表获取成功'
                    }
                }
            return Response(res, status=status.HTTP_200_OK)
            
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        """创建新部门"""
        try:
            serializer = DepartmentCreateUpdateSerializer(data=request.data)
            if serializer.is_valid():
                department = serializer.save()
                res = {
                    'status': 201,
                    'data': {
                        'id': department.id,
                        'message': '部门创建成功'
                    }
                }
                return Response(res, status=status.HTTP_201_CREATED)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, department_id=None):
        """更新部门信息"""
        try:
            if not department_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '部门ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            department = Department.objects.filter(id=department_id).first()
            if not department:
                res = {
                    'status': 404,
                    'data': {
                        'message': '部门不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            serializer = DepartmentCreateUpdateSerializer(department, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                res = {
                    'status': 200,
                    'data': {
                        'message': '部门更新成功'
                    }
                }
                return Response(res, status=status.HTTP_200_OK)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, department_id=None):
        """删除部门"""
        try:
            if not department_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '部门ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            department = Department.objects.filter(id=department_id).first()
            if not department:
                res = {
                    'status': 404,
                    'data': {
                        'message': '部门不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            department.delete()
            res = {
                'status': 200,
                'data': {
                    'message': '部门删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
